#!/usr/bin/env node

const fs = require('fs');
//需要的软件包  chalk、inquirer、 figlet、 shelljs、 yargs
const chalk = require("chalk");
const inquirer = require("inquirer");
const figlet = require("figlet");
const {createDir, createManifast,createIcoImg, createImgForlder,startZip, createIconFolder, createMoreImg, startPage, createDemoPage} = require("./libs/pwaManifast");

const { createConnection } = require('net');
require('shelljs/global');


/**
 * 获取封面版本
 * @returns Promise
 */
const getVersion = () => {
    return new Promise((resolve, reject) => {
        fs.readFile(`${__dirname}/package.json`, 'utf-8',  (err, data) => {
            if(err){
                console.log(__dirname/package.json, '<-----');
                console.error(err);
            }
            else{
                resolve(data)
            }
        }) 
    }) 
}

/**
 * 获取封面文字
 * @returns Promise
 */
const textPromise = () => {


    return new Promise(function (resolve, reject) {
        const textTypes = ['Crazy', 'Doh', 'Doom', 'Epic','block','serifcap', 'Fire Font-k', 'Fire Font-s', 'Flower Power', 'Fun Faces', 'Ghost'];
        const i = Math.floor(Math.random() * textTypes.length)

        // console.log(textTypes[i]);
        figlet.text('1902A', {
            font: textTypes[i],
            horizontalLayout: 'default',
            verticalLayout: 'default',
            width: 220,
            whitespaceBreak: true
        }, function (err, data) {

            if (err) {
                console.log('figlet run error');
                return ;
            }
            resolve(data);
        });
    })
}


var argv = require('yargs').option('p', {
    alias: 'name',
    demand: true,
    default: 'appName',
    describe: '应用名称',
    type: 'string'
})
.usage('使用文档: tools1902 [options] -p [path/img.png]')
.example(`tools1902 manifast -p ./arrow.png`,`生成 manifast.json和实例到pwa-manifast目录` )
.example(`tools1902 zip`, '对pwa-manifast文件夹进行zip打包')
.example(`tools1902 ico -p ./favicon.png`, '自动生成 favicon.ico到ico目录')
.help('h')
.alias('h', 'help')
.epilog('copyright 2021')
.command("manifast","manifast", async function (yargs) {
    
    //获取板本号
    const {version} = JSON.parse(await getVersion());
   
    //封面
 
    const colors = ["#e56045","#ffb9b2","#cc553d","#736357","#f7941d","#ffd199","#cc7b18","#53cfc8","#a1e5e2","#609996", "#00aeef",  "#8bdfff",  "#007ba9" ];
    const colorKey= Math.floor((Math.random() * colors.length));
    // console.log(colors[colorKey]);

    const text = await textPromise();
    console.log(chalk.hex(colors[colorKey])(`${text}`));

    console.log('\n');
    // console.log(chalk.hex('#e56045')(`版本号：${version}`));
    console.log(`${chalk.white.bgRed.bold(" version ")}${chalk.white.bgBlue.bold( ' '+version+' ' )} `);
    console.log('\n\n');

    
    let params = await yargs;
    const img = params.argv.p;
    
    //会话
    const {name, short_name,theme_color, background_color, display, Scope, start_url} = await inquirer
        .prompt([
            {
                name: "name",
                type: "input",
                message: "请输入APP名称(name)?",
                default : 'appName'
            },
            {
                name: "short_name",
                type: "input",
                message: "请输入APP简称(short_name)?",
                default: "short_name"
            },
            {
                name: "theme_color",
                type: "input",
                message: "主题颜色(theme_color)?",
                default: "#e56045"
            },
            {
                name: "background_color",
                type: "input",
                message: "默认背景(background_color)?",
                default: "#f2f2f2"

            },
            {
                name: "display",
                type: "list",
                choices: ["fullscreen", "standalone", "minimal-ui", "browser"],
                message: "显示模式?",
                default: "fullscreen"
            },
            {
                name: "Scope",
                type: "input",
                message: "范围?",
                default: "/"
            },
            {
                name: "start_url",
                type: "input",
                message: "启动页面?",
                default: "/startpage.html"
            }
        ]);


    //创建文件
   await createDir('pwa-manifast');

    //写入文件
    await createManifast(name, short_name, theme_color, background_color, display, Scope, start_url);

    //创建pwa-manifast/img文件夹
    await createImgForlder('pwa-manifast/img');

    //创建更多不同尺寸的图片
    await createMoreImg(img);

    //创建demo页面
    await createDemoPage();

    //创建启动页面
    await startPage(start_url);



    
    
})
.command("ico", "ico", async yargs => {

    //获取板本号
    const {version} = JSON.parse(await getVersion());    
    //封面
    const colors = ["#e56045","#ffb9b2","#cc553d","#736357","#f7941d","#ffd199","#cc7b18","#53cfc8","#a1e5e2","#609996", "#00aeef",  "#8bdfff",  "#007ba9" ];
    const colorKey= Math.floor((Math.random() * colors.length));
    
    const text = await textPromise();
    console.log(chalk.hex(colors[colorKey])(`${text}`));
    console.log('\n');
    // console.log(chalk.hex('#e56045')(`版本号：${version}`));
    console.log(`${chalk.white.bgRed.bold(" version ")}${chalk.white.bgBlue.bold( ' '+version+' ' )} `);
    console.log('\n\n');

    const arr = [{
        key: 16,
        value: '16x16'
    },
    {
        key: 32,
        value: '32x32'
    }]

    const {size} = await inquirer
    .prompt([
        {
            name: "size",
            type: "list",
            message: "ico 尺寸选择?",
            choices: ['16x16','32x32'],
            default : 16
        }
    ]);


    let key = "";
    arr.forEach((item)=> {
        if (item.value == size) {
            key = item.key
        }
    })
    let params = await yargs;
    const img = params.argv.p;

    //生成目录目录
    await createIconFolder('ico');


    
    //创建文件 
    await createIcoImg('favicon.ico',key, `${img}`);

    

})
.command("zip","jszip", async function (yargs) {
    //开始压缩
    await startZip();
})
.argv;





